# coding: utf-8
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.runtime import DeadlineExceededError
import simplejson as json, pickle

import models
from hd_commons import *

NEAREST_STATIONS_COUNT = 15

class Routes(webapp.RequestHandler):
    def get(self):
        map = get_map()

        self.response.headers['Content-Type'] = 'application/json'
        from_id = self.request.get('from_id')
        to_id = self.request.get('to_id')
        if not from_id or not to_id:            
            from_lat = float(self.request.get('from_lat'))
            from_lon = float(self.request.get('from_lon'))
            to_lat = float(self.request.get('to_lat'))
            to_lon = float(self.request.get('to_lon'))
                        
            start = get_nearest_station(map['stations'], from_lat, from_lon)
            end = get_nearest_station(map['stations'], to_lat, to_lon)
            from_id = start['id']
            to_id = end['id']
        
        routes = get_routes(map['stations'], from_id, to_id)

        ans = {'routes' : routes}            
        res_json = json.dumps(ans, ensure_ascii=False, indent=2)
        self.response.out.write(res_json)

class Routes2(webapp.RequestHandler):
    def get(self):
        map = get_map()

        self.response.headers['Content-Type'] = 'application/json'
        from_ids = [self.request.get('from_id')]
        to_ids = [self.request.get('to_id')]
        if not from_ids[0] or not to_ids[0]:      
            from_lat = float(self.request.get('from_lat'))
            from_lon = float(self.request.get('from_lon'))
            to_lat = float(self.request.get('to_lat'))
            to_lon = float(self.request.get('to_lon'))
                  
            from_station_name = get_nearest_station(map['stations'], from_lat, from_lon)['name']
            to_station_name = get_nearest_station(map['stations'], to_lat, to_lon)['name']
            from_ids = []
            to_ids = []
            for station in map['stations'].values():
                if station['name'] == from_station_name:
                    from_ids.append(station['id'])
                if station['name'] == to_station_name:
                    to_ids.append(station['id'])
            
            def get_ids(stations):
                arr = []
                for station in stations:
                    arr.append(station['id'])
                return arr
            
            #from_ids = get_ids(from_stations)
            #to_ids = get_ids(to_stations)        

        routes = []
        try:
            for i in xrange(len(from_ids)):
                for k in xrange(len(to_ids)):
                    current_routes = get_routes(map['stations'], from_ids[i], to_ids[k]) 
                    routes.extend(current_routes)
        except DeadlineExceededError:
            pass 

        # Удалить повторяющиеся маршруты
        for i in reversed(xrange(len(routes))):
            if i >= len(routes) : continue
            route = routes[i]
            for k in reversed(xrange(i)):
                route2 = routes[k]
                if route is route2: continue
                if route == route2: del routes[k]
    
        # Сортировка            
        routes.sort(key=lambda route: len(route['items']))    

        ans = {'routes' : routes}            
        res_json = json.dumps(ans, ensure_ascii=False, indent=2)
        self.response.out.write(res_json)
        
class GetStations(webapp.RequestHandler):
    def get(self):
        map = get_map()

        self.response.headers['Content-Type'] = 'application/json'
        lat = float(self.request.get('lat'))
        lon = float(self.request.get('lon'))
        
        stations = get_nearest_stations(map['stations'], lat, lon, NEAREST_STATIONS_COUNT*2)
        
        for i in reversed(xrange(len(stations))):
            if i >= len(stations): continue
            station = stations[i]
            for k in reversed(xrange(i)):
                station2 = stations[k]
                if station is station2: continue
                if station['name'] == station2['name']:
                    del stations[k]
        

        
        res_json = json.dumps(stations, ensure_ascii=False, indent=2)
        self.response.out.write(res_json)
        
application = webapp.WSGIApplication([
                                      ('/routes/', Routes2),
                                      ('/routes/1/', Routes),
                                      ('/routes/2/', Routes2),
                                      ('/get_stations/', GetStations)
                                      ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
